package com.chencidiao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class translation {
    public static void main(String[] args) {

        System.out.println("===============================");
        System.out.println("|                             |");
        System.out.println("|     英译汉   请选1            |");
        System.out.println("|     汉译英   请选2            |");
        System.out.println("===============================");
        String urlAddress =null;
        Scanner scanner = new Scanner(System.in);
        int choice=scanner.nextInt();

        if (choice==1){
            System.out.println("输入要翻译的文字:");
            String data=scanner.next();
            urlAddress= creatUrl(data, "en", "zh-CHS");//zh-CHS:中文，en:英文
             }else{
            System.out.println("输入要翻译的文字:");
            String data=scanner.next();
            urlAddress= creatUrl(data, "zh-CHS", "en");
        }

        //System.out.print("api链接为"+urlAddress);
        String urlContent=getURLContent(urlAddress);
        //System.out.println(urlContent);
        //String urlContent=getURLContent(creatUrl("teacher", "en","zh-CHS"));
Conversion(urlContent);
    }
    static String appKeyID = "7c5e69de8a45adf8";
    static String appKey = "uen4oHaiMu1oy0riJGFTJQFyacD6H0Df";

    /**
     生成有道URl@param 要搜索的词,@param 源语言,@param 目标语言
      @return
     **/
    public static String creatUrl(String query,String from,String to)
    {

        String salt = String.valueOf(System.currentTimeMillis());
        String sign = md5(appKeyID + query + salt + appKey);
        Map<String, String> params = new HashMap<String,String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("sign", sign);
        params.put("salt", salt);
        params.put("appKey", appKeyID);

        String urlStr = "https://openapi.youdao.com/api";
        return getUrlWithQueryString(urlStr, params);

    }
    //创建参数
    public static String createParam(String query,String from,String to)
    {
        String salt = String.valueOf(System.currentTimeMillis());
        String sign = md5(appKeyID + query + salt + appKey);
        Map<String, String> params = new HashMap<String,String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("sign", sign);
        params.put("salt", salt);
        params.put("appKey", appKeyID);

        String urlStr = "";
        return getUrlWithQueryString(urlStr, params);
    }
    /**
     *  生成32位md5摘要
     * @param
     * @return
     */
    public static String md5(String string)
    {
        if(string == null)
        {
            return null;
        }
        char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        byte [] btInput = string.getBytes();
        try {
            /** 获得MD5摘要算法的 MessageDigest对象 **/
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            /** 使用指定的字节更新摘要 **/
            mdInst.update(btInput);
            /** 获得密文 **/
            byte []md = mdInst.digest();
            /** 把密文转换成十六进制的字符串形式 **/
            int j = md.length;
            char str[] = new char[j*2];
            int k = 0;
            for(byte byte0 : md){
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    //获取拼接后查询的url路径
    public static String getUrlWithQueryString(String url,Map<String, String>params)
    {
        if (params == null) {
            return url;
        }

        StringBuilder builder = new StringBuilder(url);
        if (url.contains("?")) {
            builder.append("&");
        } else {
            builder.append("?");
        }

        int i = 0;
        for (String key : params.keySet()) {
            String value = params.get(key);
            if (value == null) { //过滤空key
                continue;
            }

            if (i != 0) {
                builder.append('&');
            }

            builder.append(key);
            builder.append('=');
            builder.append(encode(value));

            i++;

        }
        return builder.toString();
    }
    /**
     *  进行URL编码
     * @param input
     * @return
     */
    public static String encode(String input)
    {
        if (input == null) {
            return "";
        }

        try {
            return URLEncoder.encode(input,"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return input;
    }
    //根据url获取json，更安全
    //parm：请求的url链接  返回的是json字符串
    public static String getURLContent(String urlStr) {

        //请求的url
        URL url = null;
        //建立的http链接
        HttpURLConnection httpConn = null;
       //请求的输入流
        BufferedReader in = null;

        //输入流的缓冲
        StringBuffer sb = new StringBuffer();

        try{
            url = new URL(urlStr);

            in = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8") );

            String str = null;

            //一行一行进行读入
            while((str = in.readLine()) != null) {
                sb.append( str );
            }
        } catch (Exception ex) {

        } finally{
            try{
                if(in!=null) {
                   in.close();
                }
            }catch(IOException ex) {

            }
        }
        String result =sb.toString();
        return result;

    }
//解析json字符
    public static void Conversion(String urlContent){
        JSONObject jsonObject = JSONObject.parseObject(urlContent);
        System.out.println("查询文字为"+jsonObject.get("query"));
        Object web = jsonObject.get("web");
        String[] data = new String[3];
        JSONArray jsonArray = (JSONArray) JSONObject.toJSON(web);
        int size = jsonArray.size();
                 for (int i = 0; i < size; i++){
                         jsonObject = jsonArray.getJSONObject(i);
                        data[i]=jsonObject.getString("value");
                   }

        System.out.println("结果为"+data[0]);

    }
}


